import styles from './index.module.less';

import { useEffect, useState } from 'react';
import { Editor, Entity } from '@lle/d3-editor';
import { Tree, TreeDataNode, TreeProps } from 'antd';

interface IProps {
  editor?: Editor;
}

export const SceneList = (props: IProps) => {
  const { editor } = props;
  const [nodes, setNodes] = useState<TreeDataNode[]>([]);

  const getNodes = (entities: Entity[]) => {
    const nodes: TreeDataNode[] = [];

    entities.forEach(entity => {
      const { id, name, children, selectable } = entity;

      const node = {
        key: id,
        title: name,
        disabled: !selectable,
        children: getNodes(children),
      };
      nodes.push(node);
    });
    return nodes;
  };

  useEffect(() => {
    if (!editor) return;

    const refreshEntities = () => {
      const nodes = getNodes(editor.core.entityManager.root.children);

      setNodes(nodes);
    };

    refreshEntities();

    editor.core.bus.on('ENTITY_ADDED', refreshEntities);
    editor.core.bus.on('ENTITY_REMOVED', refreshEntities);
    editor.core.bus.on('ENTITY_MOVED', refreshEntities);
    return () => {
      editor.core.bus.off('ENTITY_ADDED', refreshEntities);
      editor.core.bus.off('ENTITY_REMOVED', refreshEntities);
      editor.core.bus.off('ENTITY_MOVED', refreshEntities);
    };
  }, [editor]);

  const onSelect: TreeProps['onSelect'] = (_selectedKeys, info) => {
    const entity = editor?.core.entityManager.getEntity(info.node.key as number);

    if (entity?.selectable) {
      editor?.core.select([entity]);
    }
  };

  return (
    <div className={styles.container}>
      <Tree onSelect={onSelect} treeData={nodes} />
    </div>
  );
};
